﻿using D.AT.Dto;
using D.AT.Events;
using D.AT.UIUitl;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.ComponentModel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;

namespace D.AT
{
    public partial class FrmAddChartResult : Form
    {
        public FrmAddChartResult()
        {
            InitializeComponent();
            this.dgvResult.SetGridDataViewStyle();
            this.dgvResult.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader;
            this.dgvResult.CellContentClick += DgvResult_CellContentClick;
        }

        private void DgvResult_CellContentClick(object? sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (this.dgvResult.Columns[e.ColumnIndex].Name == "Detail")
                {
                    //获取所在行的值
                    var index = dgvResult.Rows[0].Cells["Index"].Value;
                    if (index != null)
                    {
                        var detail = addChartResults.Where(m => m.Index == int.Parse(index.ToString())).FirstOrDefault();
                        if (detail != null)
                        {
                            txtError.Text = detail.Error;
                            txtDetail.Text = JsonConvert.SerializeObject(detail.Message);
                            JsonStr();
                            // 将光标设置到文本开始
                            txtDetail.SelectionHangingIndent = 0;
                            // 滚动到光标位置
                            txtDetail.ScrollToCaret();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("DgvResult_CellContentClick发生异常");
            }
        }

        public void CleanHistory()
        {
            try
            {

                this.lblTotalCount.Text = "0";
                this.lblSuccessTotalCount.Text = "0";
                this.lblFailTotalCount.Text = "0";

                this.dgvResult.DataSource = null;
                addChartResults = new BindingList<AddChartResult>();
                this.dgvResult.DataSource = addChartResults;
            }
            catch (Exception ex)
            {
                MessageBox.Show("CleanHistory发生异常");
            }
        }

        /// <summary>
        ///  此处必须用BindingList，否则会报错
        ///  由于需要更改数据源中的值以响应用户与表单的交互，我们重新填充列表并在每次更改时重新附加它(当它是 List<> 时)。
        ///  实现后INotifyPropertyChanged在列表中的对象上，我们使用了 BindingList<>现在绑定(bind) 一次数据并在需要时刷新
        /// </summary>
        private static BindingList<AddChartResult> addChartResults = new BindingList<AddChartResult>();

        private void FrmAddChartResult_Load(object sender, EventArgs e)
        {
            LoadColumn();

            UtilEvents.Defaut.GetEvent<AddChartEvent>().Subscribe((res) =>
            {
                this.lblTotalCount.Text = res.TotalCount.ToString();
                this.lblSuccessTotalCount.Text = res.SuccessCount.ToString();
                this.lblFailTotalCount.Text = res.FailCount.ToString();

                this.dgvResult.DataSource = null;
                addChartResults.Add(new AddChartResult()
                {
                    Index = res.Index,
                    Result = res.Result ? "OK" : "Fail",
                    Error = res.Error,
                    Message = res.Message,

                });
                this.dgvResult.DataSource = addChartResults;

            });
        }

        private void LoadColumn()
        {
            DataGridViewTextBoxColumn indexBoxColumn = new DataGridViewTextBoxColumn();
            indexBoxColumn.ReadOnly = true;
            indexBoxColumn.Name = "Index";
            indexBoxColumn.HeaderText = "序号";
            indexBoxColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            indexBoxColumn.DataPropertyName = "Index";
            dgvResult.Columns.Add(indexBoxColumn);

            DataGridViewTextBoxColumn resultBoxColumn = new DataGridViewTextBoxColumn();
            resultBoxColumn.ReadOnly = false;
            resultBoxColumn.Name = "Result";
            resultBoxColumn.HeaderText = "结果";
            resultBoxColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            resultBoxColumn.DataPropertyName = "Result";
            dgvResult.Columns.Add(resultBoxColumn);

            DataGridViewLinkColumn linkBoxColumn = new DataGridViewLinkColumn();
            linkBoxColumn.ReadOnly = true;
            linkBoxColumn.Name = "Detail";
            linkBoxColumn.HeaderText = "操作";
            linkBoxColumn.Width = 100;
            linkBoxColumn.DefaultCellStyle.NullValue = "详情";
            dgvResult.Columns.Add(linkBoxColumn);
        }

        /// <summary>
        /// 格式化Json
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnJson_Click(object sender, EventArgs e)
        {
            if (txtDetail.Text.Trim().Length == 0)
            {
                MessageBox.Show("消息内容不可为空");
                return;
            }

            try
            {
                //JObject.ToString()方法会内部调用格式化，所以直接使用即可
                JsonStr();
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误的JSON");
            }
        }

        private void JsonStr()
        {
            string json = txtDetail.Text.Trim();
            if (string.IsNullOrEmpty(json))
            {
                return;
            }

            //判读是数组还是对象
            if (json.Trim().StartsWith("["))
            {
                JArray jobj = JArray.Parse(txtDetail.Text);
                txtDetail.Text = jobj.ToString();
            }
            else if (json.Trim().StartsWith("{"))
            {
                JObject jobj = JObject.Parse(txtDetail.Text);
                txtDetail.Text = jobj.ToString();
            }
        }
    }

    public class AddChartResult
    {
        public int Index { get; set; }
        public string Result { get; set; }
        public string Error { get; set; }
        public JobAddRequestDto Message { get; set; }
    }
}
